package org.elip.stewiemaze.server;

import org.elip.stewiemaze.server.utils.Constants;
import org.elip.stewiemaze.shared.entities.Player;

import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.types.FacebookType;
import com.restfb.types.User;

public class FacebookHelper {

	public static String getUsername(String accessToken) {
		
		FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
		User user = facebookClient.fetchObject("me", User.class);
		if (user != null) {
			return user.getName();
		}
		return null;
	}
	
	public static String getUserId(String accessToken) {
		
		FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
		User user = facebookClient.fetchObject("me", User.class);
		if (user != null) {
			return user.getId();
		}
		return null;
	}
	
	public static String getEmail(String accessToken) {
		
		FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
		User user = facebookClient.fetchObject("me", User.class);
		if (user != null) {
			return user.getEmail();
		}
		return null;
	}
	
	public static User getUser(String accessToken) {
		
		FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
		User user = facebookClient.fetchObject("me", User.class);
		if (user != null) {
			return user;
		}
		return null;
	}
	
	@SuppressWarnings("unused")
	public static void publishScore(String score, String userId) {
		Long realScore = Long.valueOf(score);
		FacebookClient facebookClient = new DefaultFacebookClient(Constants.APP_ACCES_TOKEN);
		Boolean publishScoreResponse = facebookClient.publish(userId +"/scores", Boolean.class, 
				Parameter.with("score", realScore.intValue()));
	}

	@SuppressWarnings("unused")
	public static void postScoreToWall(String username, String score) {
		
		Player player = DatastoreHelper.getPlayer(username);
		
		String accessToken = player.getAccessToken();
		
		FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
		FacebookType postScoreToWallResponse = facebookClient.publish("me/feed", FacebookType.class, 
				Parameter.with("message", "just scored " + score + " on stewiemaze"));
		
	}
	
	@SuppressWarnings("unused")
	public static void postMessageToWall(String username, String message) {
		
		Player player = DatastoreHelper.getPlayer(username);
		
		Long realScore = player.getHighscore();
		
		String accessToken = player.getAccessToken();
		String score = player.getHighscore() + "";
		
		FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
		FacebookType postScoreToWallResponse = facebookClient.publish("me/feed", FacebookType.class, 
				Parameter.with("message", message));
		
	}

}
